package com.lxw.nonghe.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.annotation.RequiresPermission;
import com.lxw.nonghe.common.Result;
import com.lxw.nonghe.entity.PolicyAttachment;
import com.lxw.nonghe.service.PolicyAttachmentService;
import com.lxw.nonghe.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 政策附件表 前端控制器
 * </p>
 *
 * @author lxw
 * @since 2025-05-14
 */
@RestController
@RequestMapping("/policyAttachment")
@RequiresPermission("policyAttachment:manage")
public class PolicyAttachmentController {

    @Autowired
    private PolicyAttachmentService attachmentService;

    @Autowired
    private LogUtils logUtils;

    private static final String UPLOAD_DIR = "uploads/policy/";

    @PostMapping("/upload")
    public Result<PolicyAttachment> uploadAttachment(
            @RequestParam("file") MultipartFile file,
            @RequestParam("policyId") Integer policyId) {
        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(uniqueFilename);

            // 保存文件
            Files.write(filePath, file.getBytes());

            // 保存附件信息到数据库
            PolicyAttachment attachment = new PolicyAttachment();
            attachment.setPolicyId(policyId);
            attachment.setAttachmentName(originalFilename);
            attachment.setAttachmentPath(UPLOAD_DIR + uniqueFilename);
            attachment.setCreateTime(new Date());

            attachmentService.save(attachment);

            logUtils.recordLog("政策附件管理", "上传附件", "成功",
                    "政策ID:" + policyId + ", 附件名称:" + originalFilename);

            return Result.success("政策附件上传成功", attachment);
        } catch (IOException e) {
            logUtils.recordLog("政策附件管理", "上传附件", "失败", e.getMessage());
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "上传附件", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteAttachment(@PathVariable Integer id) {
        try {
            PolicyAttachment attachment = attachmentService.getById(id);
            if (attachment == null) {
                logUtils.recordLog("政策附件管理", "删除附件", "失败", "附件ID:" + id + "不存在");
                return Result.error("未找到该政策附件");
            }

            // 删除物理文件
            Path filePath = Paths.get(attachment.getAttachmentPath());
            if (Files.exists(filePath)) {
                Files.delete(filePath);
            }

            // 删除数据库记录
            boolean result = attachmentService.removeById(id);

            if (result) {
                logUtils.recordLog("政策附件管理", "删除附件", "成功",
                        "附件ID:" + id + ", 政策ID:" + attachment.getPolicyId());
                return Result.success("政策附件删除成功", true);
            } else {
                logUtils.recordLog("政策附件管理", "删除附件", "失败", "数据库记录删除失败");
                return Result.error("政策附件删除失败");
            }
        } catch (IOException e) {
            logUtils.recordLog("政策附件管理", "删除附件", "失败", e.getMessage());
            return Result.error("文件删除失败: " + e.getMessage());
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "删除附件", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result<Boolean> updateAttachment(@RequestBody PolicyAttachment attachment) {
        try {
            boolean result = attachmentService.updateById(attachment);
            if (result) {
                logUtils.recordLog("政策附件管理", "更新附件", "成功",
                        "附件ID:" + attachment.getAttachmentId());
                return Result.success("政策附件更新成功", true);
            } else {
                logUtils.recordLog("政策附件管理", "更新附件", "失败",
                        "附件ID:" + attachment.getAttachmentId() + "不存在");
                return Result.error("政策附件更新失败");
            }
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "更新附件", "失败", e.getMessage());
            return Result.error("系统异常: " + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public Result<PolicyAttachment> getAttachmentById(@PathVariable Integer id) {
        try {
            PolicyAttachment attachment = attachmentService.getById(id);
            if (attachment != null) {
                return Result.success("政策附件查询成功", attachment);
            } else {
                logUtils.recordLog("政策附件管理", "查询附件详情", "失败", "附件ID:" + id + "不存在");
                return Result.error("未找到该政策附件");
            }
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "查询附件详情", "失败", e.getMessage());
            return Result.error("查询异常: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<Page<PolicyAttachment>> getAttachmentPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer policyId,
            @RequestParam(required = false) String attachmentName) {
        try {
            Page<PolicyAttachment> page = attachmentService.getAttachmentPage(
                    current, size, policyId, attachmentName);
            return Result.success("政策附件分页查询成功", page);
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "分页查询附件", "失败", e.getMessage());
            return Result.error("分页查询异常: " + e.getMessage());
        }
    }
    // 条件查询方法
    @PostMapping("/query")
    public Result<Page<PolicyAttachment>> queryAttachments(
            @RequestBody PolicyAttachment queryParam,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<PolicyAttachment> page = attachmentService.queryAttachments(
                    queryParam, current, size);
            return Result.success("政策附件条件查询成功", page);
        } catch (Exception e) {
            logUtils.recordLog("政策附件管理", "条件查询附件", "失败", e.getMessage());
            return Result.error("条件查询异常: " + e.getMessage());
        }
    }
}
